package com.darrenchan.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-08-30 10:41
 */
public class StringThread {
    volatile static int index = 0;
    static String str = "我爱北京天安门";

    static void Main() {
        new Thread(() -> {
            while (index < str.length()) {
                if (index % 2 == 1) continue;
                if (index < str.length())System.out.println(Thread.currentThread() + ":" + str.charAt(index));
                index++;
            }
        }).start();

        new Thread(() -> {
            while (index < str.length()) {
                if (index % 2 == 0) continue;
                if (index < str.length())System.out.println(Thread.currentThread() + ":" + str.charAt(index));
                index++;
            }
        }).start();
    }

    static void Main2() {
        new Thread(() -> {
            synchronized (str) {
                while (index < str.length()) {
                    if(index % 2 == 0) {
                        System.out.println(Thread.currentThread() + ":" + str.charAt(index));
                        index++;
                        str.notify();
                    } else {
                        try {
                            str.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (str) {
                while (index < str.length()) {
                    if(index % 2 == 1) {
                        System.out.println(Thread.currentThread() + ":" + str.charAt(index));
                        index++;
                        str.notify();
                    } else {
                        try {
                            str.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    public static void main(String[] args) {
        Main2();
    }
}
